package com.github.postsanf.yinian.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.LocalAlbumSelectAdapter2;
import com.github.postsanf.yinian.bean.YNFileComparator;
import com.github.postsanf.yinian.bean.YNFileInfo;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.Crop;
import com.github.postsanf.yinian.utils.ImageUtils;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * 发布相册管理页面
 */
public class LocalAlbumActivity2 extends BaseActivity implements View.OnClickListener {
    private LocalAlbumSelectAdapter2 mAdapter;                        // 相册适配器
    private GridView mGirdView;                        // 网格布局
    private File mImgDir;                        // 图片数量最多的文件夹
    private List<String> mImgs = new ArrayList<>();                            // 所有的图片
    private TextView mPreview;                        // 预览
    private TextView mUpLoad;                            // 上传

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        registerBoradcastReceiver();
        setContentView(R.layout.yn_activity_local_album);
        initView();
        YNImageFloder ynImageFloder = (YNImageFloder) getIntent().getSerializableExtra(LocalAlbumActivity2.class.getSimpleName());
        initSelected(ynImageFloder);
    }

    private void initView() {
        mUpLoad = (TextView) findViewById(R.id.btn_album_manage_sure);
        mGirdView = (GridView) findViewById(R.id.gv_album_gridView);
        mPreview = (TextView) findViewById(R.id.btn_album_manage_preview);
        findViewById(R.id.timegood_back).setOnClickListener(this);
        mUpLoad.setOnClickListener(this);
        mPreview.setOnClickListener(this);
    }

    private String switchSure(int val) {
        return val == 0 ? "" : "(" + val + ")";
    }


    public void initSelected(YNImageFloder floder) {
        mImgDir = new File(floder.getDir());
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        File[] files = mImgDir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                String filename = file.getName().toLowerCase();
                if (file.length() > 0 && !filename.contains(".9")) {
                    if (filename.endsWith(".jpg") || filename.endsWith(".png")
                            || filename.endsWith(".jpeg"))
                        return true;
                }
                return false;
            }
        });
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String imgPath = file.getPath();
            double imgLat = 0.0, imgLong = 0.0;
            boolean flag = true;
            float[] arr = new float[2];
            try {
                //android读取图片EXIF信息
                ExifInterface exifInterface = new ExifInterface(imgPath);
                flag = exifInterface.getLatLong(arr);
                imgLat = arr[0];
                imgLong = arr[1];
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.length() > 0) {
                YNFileInfo fileInfo = new YNFileInfo();
                fileInfo.setName(file.getName());
                fileInfo.setPath(file.getPath());
                fileInfo.setLatitude(imgLat);
                fileInfo.setLongitude(imgLong);
                fileInfo.setLastModified(file.lastModified());
                fileList.add(fileInfo);
            }
        }
        Collections.sort(fileList, new YNFileComparator());
        mImgs.clear();
        for (int j = 0; j < fileList.size(); j++) {
            mImgs.add(fileList.get(j).getName());
        }
        mAdapter = new LocalAlbumSelectAdapter2(this, mImgs,
                R.layout.yn_album_grid_item, mImgDir.getAbsolutePath(), this);
        mGirdView.setAdapter(mAdapter);
    }

    public void setSureCount(int totals) {
        mUpLoad.setText("上传" + switchSure(totals));
        mPreview.setText("预览" + switchSure(totals));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_album_manage_sure:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再上传");
                    return;
                }
                if (MainActivity.goodsid == 3) {
                    startActivity(new Intent(this, TimeGoodsDrawActivity.class).putExtra("goodsPic", SelectedImg.mSelectedImage.get(0)));
                    finish();
                } else if (MainActivity.goodsid == 4) {
                    startActivity(new Intent(this, TimeGoodsJointActivity.class).putExtra("goodsPic", SelectedImg.mSelectedImage.get(0)));
                    finish();
                }
                break;
            case R.id.btn_album_manage_preview:
                if (SelectedImg.mSelectedImage.size() <= 0) {
                    showToast("请选择相片后再预览");
                    return;
                }
                Intent toPreview = new Intent(this, PreviewActivity.class);
                startActivity(toPreview);
                break;
            case R.id.timegood_back:
                finish();
                break;
            default:
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case ImageUtils.REQUEST_CODE_FROM_CAMERA:
                if (resultCode == RESULT_CANCELED) {
                    ImageUtils.deleteImageUri(this, ImageUtils.imageUriFromCamera);
                } else {
                    Uri imageUriCamera = ImageUtils.imageUriFromCamera;
//                    SelectedImg.mSelectedImage.add(ImageUtils.getImageAbsolutePath19(this, imageUriCamera));
                    String camerUrl = ImageUtils.getImageAbsolutePath19(this, imageUriCamera);
                    Intent intent = new Intent(LocalAlbumActivity2.this, VoiceCardEditActivity.class);
                    intent.putExtra("imagelocal", camerUrl);
                    Uri Uri = android.net.Uri.parse("file:///" + camerUrl);
//                    beginCrop(Uri);
                }
                break;
            case Crop.REQUEST_CROP:
//                handleCrop(resultCode, data);
                break;
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        AnimateFirstDisplayListener.displayedImages.clear();
        super.onBackPressed();
    }

    /**
     * 图片加载监听事件
     **/
    public static class AnimateFirstDisplayListener extends
            SimpleImageLoadingListener {

        public static final List<String> displayedImages = Collections
                .synchronizedList(new LinkedList<String>());

        @Override
        public void onLoadingComplete(String imageUri, View view,
                                      Bitmap loadedImage) {
            if (loadedImage != null) {
                ImageView imageView = (ImageView) view;
                boolean firstDisplay = !displayedImages.contains(imageUri);
                if (firstDisplay) {
                    displayedImages.add(imageUri); // 将图片uri添加到集合中
                }
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setSureCount(SelectedImg.mSelectedImage.size());
        mAdapter.notifyDataSetChanged();
    }

    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    setSureCount(SelectedImg.mSelectedImage.size());
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateUpNum);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        AnimateFirstDisplayListener.displayedImages.clear();
        SelectedImg.mSelectedImage.clear();
        this.unregisterReceiver(mBroadcastReceiver);
        super.onDestroy();
    }


    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
